package com.gsit.expenditure.services;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.gsit.expenditure.domain.Bill;
import com.gsit.expenditure.domain.Customer;
import com.gsit.expenditure.domain.TravelBill;
import com.gsit.expenditure.domain.Vehicle;
import com.gsit.expenditure.utils.BillStatus;

@Repository("billService")
public class BillService {
	
	@PersistenceContext
	private EntityManager entityManager;

	
	@Transactional
	public <T> T find(Class<T> entityClass, Long id) {
		return entityManager.find(entityClass, id);
	}

	@Transactional
	public void saveOrUpdateBill(Bill billEntity) {
		
		entityManager.merge(billEntity);
	}
	
	
	@Transactional
	public void delete(Bill billEntity) {
		entityManager.remove(entityManager.merge(billEntity));
	}
	
	@Transactional
	public List<Customer> findCustomerName(){
		Query query=entityManager.createQuery("select customer from Customer customer");
		return query.getResultList();
	}
	
	@Transactional
	public List<Vehicle> findVehicleName(){
		Query query=entityManager.createQuery("select vehicle from Vehicle vehicle");
		return query.getResultList();
	}
	
	@Transactional
	public List<TravelBill> onSearch(){
		Query query=entityManager.createQuery("select travelBill from TravelBill  travelBill");
		return query.getResultList();
	}
	

	@Transactional
	public List<Bill> findAllBill() {
		
		Query query = entityManager.createNamedQuery("Bill.findAll", Bill.class);
		query.setParameter("status" , BillStatus.NEW);
		return query.getResultList();
	}
	

	@Transactional
	public List<Bill> findBillBetweenDates(String fromDate , String toDate) {
		Query query = entityManager.createQuery("select bill from Bill  bill where  bill.status = 'NEW' and bill.billDate  between  DATE('"+fromDate+"')  AND   DATE('"+toDate+"') order by bill.billDate ASC" );
		return query.getResultList();
	}
	
	@Transactional
	public List<Bill> findBillByConsumerAndBillDate(Long customer, BillStatus status, String fromDate, String toDate) {
		String sql = "select bill from Bill  bill where  bill.status = 'NEW' and bill.customer = "+customer;
		
		if(fromDate != null && !fromDate.trim().equals("")  && toDate != null && !toDate.trim().equals("") ){
			sql += " and bill.billDate  between  DATE('"+fromDate+"')  AND   DATE('"+toDate+"')";
		}
		if(status != null ){
			sql += " and bill.status = '"+status+"'";
		}
		sql += " order by bill.billDate ASC" ;
		
		Query query = entityManager.createQuery(sql);
		return query.getResultList();
	}
	
	
}
